var geoDao = require('../daos/geoDao'),
	idService = require('./idService');

// -------------------------- CRUD SERVICES ----------------------------

module.exports.getAll = function (short, callback) {
	geoDao.getAll(short, callback);
}

module.exports.find = function (filters, callback) {
	geoDao.find(filters, callback);
}

module.exports.findOne = function (filters, callback) {
	geoDao.findOne(filters, callback);
}

module.exports.save = function (geo, callback) {
	geo = copyGeometricalDataToGeospatial(geo);
	if (!geo.id) {
		idService.getId('geos', function(err, geoId) {
			if (err) {
				callback(err);
				return;
			}
			if (geoId) {
				geo.id = geoId;
				geoDao.upsert(geo.id, geo, function(err) {
					if (err)
						callback(err);
					else
						callback(false, geo);
				});
			} else {
				console.log('ERROR: geoService save. Detalle: ' + err);
		  	  	callback(err);
			}
		});
	} else {
		geoDao.upsert(geo.id, geo, function(err) {
			if (err)
				callback(err);
			else
				callback(false, geo);
		});
	}
}

module.exports.remove = function (id, callback) {
	geoDao.remove(id, callback);
}

function copyGeometricalDataToGeospatial(geoData) {
	if (geoData.features) {
		geoData.geospatial = {};
		geoData.features.forEach(function (feature) {
			if (feature.geometry.type) {
				if (feature.geometry.type == 'Point') {
					geoData.geospatial.point = feature.geometry.coordinates;
				}
				if (feature.geometry.type == 'Polygon') {
					geoData.geospatial.multipoint = [];
					feature.geometry.coordinates[0].forEach(function (point) {
						geoData.geospatial.multipoint.push({point: point});
					});
				}
			}
		});
	}
	return geoData;
}